import * as vscode from "vscode";
import { join, dirname,normalize } from "path";
import { existsSync, readFileSync } from "fs";

export class UseModelHoverProvider implements vscode.HoverProvider {
  provideHover(document: vscode.TextDocument, position: vscode.Position) {
    const fileName    = document.fileName;
    const workDir     = dirname(fileName);
    const word        = document.getText(document.getWordRangeAtPosition(position));
    const line:any        = document.lineAt(position);

    if (!line.text.includes("useModel") || !word) {
      return;
    }

    let workspacePath = "";
    if (vscode.workspace.workspaceFolders?.length) {
      workspacePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
      workspacePath = normalize(workspacePath);
    }

    const cwd = workspacePath;

    let ProviderPath: string = join(
      cwd,
      "src",
      ".umi",
      "plugin-model",
      "model.ts"
    );

    try {
      const ProviderFile = readFileSync(ProviderPath).toString();

      if (ProviderFile.indexOf(word) === -1) {
        return;
      }

      const numRegex = new RegExp(`from\s*(.*)${word}'`, "g");

      const match: any = ProviderFile.match(numRegex);
      if (!match[0]) {
        return;
      }
      const pstr:string = match[0];
      const uri:string = pstr.replace('from','').replace(/'/g,'').trim();

      let definitionFile = "";
      if (existsSync(`${uri}.ts`)) {
        definitionFile = `${uri}.ts`;
      } else if (existsSync(`${uri}.tsx`)) {
        definitionFile = `${uri}.tsx`;
      } else if (existsSync(`${uri}.js`)) {
        definitionFile = `${uri}.js`;
      } else if (existsSync(`${uri}.jsx`)) {
        definitionFile = `${uri}.jsx`;
      }
  
      if (existsSync(definitionFile)) {
        return new vscode.Hover(`#### 模型：${word}
[${definitionFile}](${vscode.Uri.file(definitionFile)})
`);
      }
    } catch (error) {
      console.log("===================");
      console.log(error);
      console.log("===================");
    }

    
  }
}
